package com.ourhours.message.listener;

import com.alibaba.fastjson.JSON;
import com.ourhours.message.constant.ConstantMQ;
import com.ourhours.message.dto.EmailDto;
import com.ourhours.message.enums.ApiResponseCode;
import com.ourhours.message.exception.MessageException;
import com.ourhours.message.service.EmailSendService;
import com.ourhours.redismq.AbstarctMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class EmailMqListener extends AbstarctMessageHandler {

    @Autowired
    EmailSendService emailSendService;
    public EmailMqListener() {
        // 说明该handler监控的消息类型，第一个参数是队列名称，第二个参数为重试次数
        super(ConstantMQ.emailMQ, 1);
    }
    @Override
    public void handle(String text) {
        EmailDto dto = null;
        try {
            dto = JSON.parseObject(text, EmailDto.class);
            if (dto == null || (dto.getId() == null && dto.getVendorId() == null)) {
                throw new MessageException("接收的报文格式不对，转型后结果为null");
            }
            emailSendService.sendEmail(dto);
            log.info("==>EmailMqListener.handle 监听MQ报文为:{}，调用发送邮件service运行完毕！", text);
            emailSendService.setEmailSendStatus(dto.getId(), 1, null, null);
        } catch (Exception e) {
            log.error("==>EmailMqListener.handle 监听MQ报文为:{}，调用发送邮件service运行异常:{}", text, e);
            if (dto != null && dto.getId() != null) {
                emailSendService.setEmailSendStatus(dto.getId(), -1, ApiResponseCode.ERROR.getCode(), e.getMessage());
            }
        }
    }

    @Override
    public void handleFailed(String s) {

    }

//    @JmsListener(destination = ConstantMQ.emailMQ)
//    public void receiveQueueForEmail(String text) {
//        EmailDto dto = null;
//        try {
//            dto = JSON.parseObject(text, EmailDto.class);
//            if (dto == null || (dto.getId() == null && dto.getVendorId() == null)) {
//                throw new MessageException("接收的报文格式不对，转型后结果为null");
//            }
//            emailSendService.sendEmail(dto);
//            log.info("==>EmailMqListener.receiveQueueForEmail 监听MQ报文为:{}，调用发送邮件service运行完毕！", text);
//            emailSendService.setEmailSendStatus(dto.getId(), 1, null, null);
//        } catch (Exception e) {
//            log.error("==>EmailMqListener.receiveQueueForEmail 监听MQ报文为:{}，调用发送邮件service运行异常:{}", text, e);
//            if (dto != null && dto.getId() != null) {
//                emailSendService.setEmailSendStatus(dto.getId(), -1, ApiResponseCode.ERROR.getCode(), e.getMessage());
//            }
//        }
//    }
}
